When you run a Java program, Java needs memory to:
Mnemonic to Remember: JVM is like a "Janitor Vacuuming Messes" β it cleans up automatically so you don't have to worry about forgetting to free memory.
Imagine your computer is a house:
Easy to Remember: Heap for "Heavy Objects", Stack for "Short-term Stuff".
new keywordMnemonic: Heap = "Huge Elderly Area for Persistent Stuff" (Young for new, Old for survivors).
String name = new String("Deepak");
π Result:
One "Deepak" in String Pool + another new object in Heap.
String s1 = "Hello"; String s2 = "Hello";
π Result: Both s1 and s2 point to the same object in
String Pool, no duplicate created.
String s1 = new String("World");
String s2 = s1.intern();
String s3 = "World";
π Result:
s2 and s3 refer to the same object in
String Pool, but s1 is a separate object in Heap.
π Important Notes on Heap & String Pool:
String objects.intern()intern() is a method of String class.
String x = new String("Java");
String y = x.intern();
String z = "Java";
System.out.println(x == y); // false
System.out.println(y == z); // true
π Why use intern()?
Mnemonic: Stack = "Swift Temporary Area for Calls and Keywords" (LIFO like a stack of books).
int a = 10;
π Result: 'a' is a local variable, stored in Stack
Mnemonic: Method Area = "Master Archive for Templates and Statics".
static int collegeCode = 123;
π Result: 'collegeCode' is stored in the Method Area
Mnemonic: PC Register = "Personal Compass for Running Instructions".
Mnemonic: Native Stack = "Niche Space for External Tools".
public class Student {
int age = 20; // Stored in Heap
static String school = "ABC"; // Stored in Method Area
public static void main(String[] args) {
int roll = 101; // Stored in Stack
Student s1 = new Student(); // Object in Heap, ref in Stack
}
}
| Memory Area | What It Stores |
|---|---|
| Heap | Object s1, instance variable age |
| Stack | roll, reference to s1 |
| Method Area | Class info, school |
free() like in C/C++Mnemonic: GC = "Garbage Cleaner" β like a robot vacuum that runs when the room (heap) is messy.
Student s1 = new Student();
s1 = null; // Now the object is not used β eligible for GC
You can suggest GC like this:
System.gc(); // Suggests garbage collection (not guaranteed)
| β Question | β Simple Answer |
|---|---|
| What is memory management? | Java automatically allocates and frees memory using JVM. |
| What is the Heap? | Stores objects. Shared by all. Cleaned by garbage collector. |
| What is Stack memory? | Stores method calls and local variables. One per thread. |
| What is garbage collection? | JVM removes unused objects from memory automatically. |
| Where are static variables stored? | In the Method Area. |
| What is stored in Stack vs Heap? | Stack = local vars, refs. Heap = objects. |
| Can you force GC in Java? | You can suggest it using System.gc(), but it's not guaranteed. |
Test your understanding with these expandable questions. Click to reveal answers.
Heap stores objects (shared, GC managed), Stack stores local vars and method calls (per thread, LIFO).
When it has no live references (null or out of scope).
Young: New objects (Eden + Survivors), Old: Long-lived objects promoted after surviving GC cycles.
GC pauses all threads to collect garbage safely.
Strong (default), Soft (collected when low memory), Weak (collected eagerly), Phantom (for cleanup).
These are commonly asked questions in interviews, compiled from sources like Baeldung, Medium, JavaCodeGeeks, and in28minutes.
| β Question | β Answer |
|---|---|
| What Does the Statement βMemory Is Managed in Javaβ Mean? | Java uses JVM and GC for automatic allocation/deallocation, unlike C where it's manual. |
| What Is Garbage Collection and What Are Its Advantages? | Process to reclaim unused memory. Advantages: No manual free, prevents leaks, focus on logic. |
| Are There Any Disadvantages of Garbage Collection? | Performance impact due to pauses; tune with algorithms like G1 or ZGC. |
| What Is the Meaning of the Term βStop-The-Worldβ? | Application pauses during GC to allow safe collection. |
| What Are Stack and Heap? What Is Stored in Each? | Stack: Local vars, method calls. Heap: Objects, shared. |
| Describe Generational Garbage Collection. | Heap divided into Young (Eden, Survivors) and Old; minor GC for Young, major for Old. |
| When Does an Object Become Eligible for Garbage Collection? | No live references; null, scope end, or circular without external refs. |
| How Do You Trigger Garbage Collection from Java Code? | System.gc() suggests, but not forced. |
| What Happens When There Is Not Enough Heap Space? | OutOfMemoryError thrown. |
| Is It Possible to βResurrectβ an Object Eligible for GC? | Yes, in finalize() by assigning to static, but only once. |
| Describe Strong, Weak, Soft, and Phantom References. | Strong: Prevents GC. Soft: GC when low mem. Weak: Eager GC. Phantom: For post-GC cleanup. |
| Can Circular References Be GC'ed? | Yes, if unreachable from roots. |
| How Are Strings Represented in Memory? | As objects with char[] and hash; constants in string pool. |
| What Is StringBuilder? Difference from + and StringBuffer? | Mutable string manipulation. + creates new strings. StringBuffer is thread-safe. |
| What is the Java Memory Model? | Defines thread-memory interactions for visibility and synchronization. |
| Describe the different parts of the Java heap memory. | Young (Eden, S0, S1), Old, Metaspace. |
| How does the garbage collector know which objects to collect? | Using marking (reachable from roots) and sweeping. |
| What is a memory leak in Java, and how can it be prevented? | Unused objects retained by references. Prevent by nullifying refs, using tools like MAT. |
| What is the difference between the finalize() method and Cleaner/PhantomReference? | finalize() deprecated, unreliable. Cleaner/Phantom for reliable cleanup. |
| How is Java different from C & C++ in terms of memory management? | Automatic vs manual allocation/free. |
| Why Are Memory Leaks Rare in Java? | Due to automatic GC. |
| What Are Generations in Java Garbage Collection? | Young and Old for efficient GC based on object lifespan. |
| What Are the Types of Garbage Collectors in Java? | Serial, Parallel, G1, ZGC. |
| Why is finalize() Method Deprecated in Java 9? | Unreliable, performance issues; use try-with-resources or Cleaner. |
| Part | Description | Example |
|---|---|---|
| Heap | Stores objects | new Student() |
| Stack | Stores method calls and variables | int a = 5; |
| Method Area | Stores class data, static vars | static int x; |
| Garbage Collection | Removes unused objects | obj = null; |